import 'package:flutter/material.dart';

class MemoryOperationPage extends StatefulWidget {
  final double memoryValue;
  final Function(double) onUpdate;

  const MemoryOperationPage({
    super.key,
    required this.memoryValue,
    required this.onUpdate,
  });

  @override
  State<MemoryOperationPage> createState() => _MemoryOperationPageState();
}

class _MemoryOperationPageState extends State<MemoryOperationPage> {
  late double _currentValue;

  @override
  void initState() {
    super.initState();
    _currentValue = widget.memoryValue;
  }

  void _clearMemory() {
    _updateValue(0);
  }

  void _updateValue(double newValue) {
    setState(() {
      _currentValue = newValue;
    });
    widget.onUpdate(newValue);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('内存操作')),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '当前内存值: ${_currentValue.toString()}',
              style: const TextStyle(fontSize: 24),
            ),
            const SizedBox(height: 20),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: () => _updateValue(_currentValue + 1),
                  child: const Text('M+1'),
                ),
                ElevatedButton(
                  onPressed: () => _updateValue(_currentValue + _currentValue),
                  child: const Text('M+'),
                ),
              ],
            ),
            const SizedBox(height: 10),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: [
                ElevatedButton(
                  onPressed: () => _updateValue(_currentValue - 1),
                  child: const Text('M-1'),
                ),
                ElevatedButton(
                  onPressed: () => _updateValue(_currentValue - _currentValue),
                  child: const Text('M-'),
                ),
              ],
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: _clearMemory,
              child: const Text('清零'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.red,
                foregroundColor: Colors.white,
              ),
            ),
            const SizedBox(height: 10),
            ElevatedButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('返回计算器'),
            ),
          ],
        ),
      ),
    );
  }
}
